<template>
	<form-container
		:title="formData.id ? '编辑角色' : '增加角色'"
		:width="700"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-form-item label="角色名称：" name="name">
				<a-input v-model:value="formData.name" placeholder="请输入角色名称" allow-clear />
			</a-form-item>
			<a-form-item label="角色分类：" name="category">
				<a-select
					v-model:value="formData.category"
					:options="categoryOptions"
					style="width: 100%"
					placeholder="请选择角色分类"
				>
				</a-select>
			</a-form-item>
			<a-form-item v-if="formData.category === 'ORG'" label="所属机构：" name="orgId">
				<a-tree-select
					v-model:value="formData.orgId"
					style="width: 100%"
					:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
					placeholder="请选择组织"
					allow-clear
					tree-default-expand-all
					:tree-data="treeData"
					:field-names="{
						children: 'children',
						label: 'name',
						value: 'id'
					}"
					selectable="false"
					tree-line
				></a-tree-select>
			</a-form-item>
			<a-form-item label="默认数据范围：" name="dataScope">
				<a-radio-group v-model:value="radioGroupValue" name="radioGroup" @change="(evt) => changeDataScope(evt)">
					<a-radio
						v-for="(item, index) in defaultDatascope"
						:key="index"
						:name="item.scopeCategory"
						:value="item.level"
					>
						<a-badge
							v-if="
								(item.scopeCategory === 'SCOPE_ORG_DEFINE') &
								(radioGroupValue === 3) &
								(item.scopeDefineOrgIdList !== undefined)
							"
							:count="item.scopeDefineOrgIdList.length"
							:number-style="{ backgroundColor: '#52c41a' }"
						>
							{{ item.title }}
						</a-badge>
						<div v-else>{{ item.title }}</div>
					</a-radio>
				</a-radio-group>
				<a-button v-if="radioGroupValue === 3" type="link" size="small" @click="handleDefineOrg(defaultDatascope[4])"
					>选择机构
				</a-button>
			</a-form-item>
			<a-form-item label="排序：" name="sortCode">
				<a-slider v-model:value="formData.sortCode" :max="100" />
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" :loading="submitLoading" @click="onSubmit">保存</a-button>
		</template>
		<ScopeDefineOrg ref="scopeDefineOrgModal" @click="scopeDefineOrgClick" />
	</form-container>
</template>

<script setup name="roleForm">
	import { required } from '@/utils/formRules'
	import { getCurrentInstance } from 'vue'
	import orgApi from '@/api/sys/orgApi'
	import roleApi from '@/api/sys/roleApi'
	import ScopeDefineOrg from './scopeDefineOrg.vue'
	import tool from '@/utils/tool'
	import { defaultDatascope } from './roleConst'
	// 定义emit事件
	const emit = defineEmits({ successful: null })
	// 默认是关闭状态
	let visible = ref(false)
	const formRef = ref()
	// 表单数据，也就是默认给一些数据
	const formData = ref({})
	// 定义机构元素
	const treeData = ref([])
	const submitLoading = ref(false)
	const scopeDefineOrgModal = ref(null)

	const radioGroupValue = ref(5)
	// 打开抽屉
	const onOpen = (record, orgId) => {
		visible.value = true
		formData.value = {
			sortCode: 99,
			orgId: orgId,
			category: orgId ? categoryOptions[1].value : categoryOptions[0].value,
			dataScope: radioGroupValue.value,
			defaultDataScope: defaultDatascope.find((f) => f.level === 5) //找数据范围
		}
		if (record) {
			//遍历默认数据权限
			defaultDatascope.forEach((item) => {
				//如果数据范围等级一样就选中否则就取消选中
				if (item.level === record.defaultDataScope.level) {
					radioGroupValue.value = item.level
					formData.value.dataScope = item.level
					item.scopeDefineOrgIdList = record.defaultDataScope.scopeDefineOrgIdList //赋值数据范围
				}
			})
			formData.value = Object.assign(formData.value, record)
			console.log(formData.value)
		}
		// 获取机构树并加入顶级
		orgApi.orgTree().then((res) => {
			treeData.value = res
		})
	}
	// 关闭抽屉
	const onClose = () => {
		visible.value = false
	}
	// 默认要校验的
	const formRules = {
		orgId: [required('请选择所属组织')],
		name: [required('请输入角色名称')],
		category: [required('请选择角色分类')],
		dataScope: [required('请输入默认数据范围')],
		sortCode: [required('请选择排序')]
	}
	// 机构分类字典
	let categoryOptions = tool.dictList('ROLE_CATEGORY')
	// 验证并提交数据
	const onSubmit = () => {
		formRef.value.validate().then(() => {
			submitLoading.value = true
			roleApi
				.submitForm(formData.value, formData.value.id)
				.then(() => {
					visible.value = false
					emit('successful')
				})
				.finally(() => {
					submitLoading.value = false
					radioGroupValue.value = defaultDatascope[0].level //恢复默认数据范围为全部
				})
		})
	}
	// 点击数据权限选择
	const changeDataScope = (evt) => {
		let checked = evt.target.checked
		if (checked) {
			radioGroupValue.value = evt.target.value //设置按钮值
			formData.value.dataScope = evt.target.value
			const data = defaultDatascope.find((f) => f.level === evt.target.value) //找数据范围
			formData.value.defaultDatascope = data //设置数据范围
		}
	}

	// 处理自定义
	const handleDefineOrg = (recordDataScope) => {
		// 选中了自定义
		if (recordDataScope.level === 3) {
			// 获取到选中的key数组，传过去，让其那边回显
			const checkKeysStr = recordDataScope.scopeDefineOrgIdList
			scopeDefineOrgModal.value.onOpen(recordDataScope.level, checkKeysStr)
		} else {
			// 清理缓存中的结构,去掉就行
			handleDatascope(false, null)
		}
	}
	// 自定义数据弹窗回调
	const scopeDefineOrgClick = (value) => {
		handleDatascope(true, value.defineOrgIdData.scopeDefineOrgIdList)
	}
	// 处理Datascope数据被选中自定义或取消自定义数据
	const handleDatascope = (check, orgData) => {
		defaultDatascope.forEach((item) => {
			if (item.scopeCategory === 'SCOPE_ORG_DEFINE') {
				if (check) {
					item.scopeDefineOrgIdList = orgData //更新自定义数据范围机构列表
					formData.value.defaultDataScope = item //设置默认数据范围为自定义
				} else {
					item.scopeDefineOrgIdList = []
				}
			}
		})
	}
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})
</script>
